<template>
  <div class="exam-result-container">
    <div class="back-link">
      <router-link to="/exams">
        <i class="el-icon-arrow-left"></i> 返回考试列表
      </router-link>
    </div>
    
    <el-card class="result-card">
      <div class="result-header">
        <h2 class="exam-title">{{ exam.title }}</h2>
        <div class="exam-meta">
          <span class="course-name">{{ exam.courseName }}</span>
          <span class="exam-type">{{ getExamTypeText(exam.type) }}</span>
          <span class="exam-time">{{ formatDateTime(exam.startTime) }} - {{ formatDateTime(exam.endTime) }}</span>
        </div>
      </div>
      
      <div class="result-summary">
        <div class="score-section">
          <div class="score-circle" :class="getScoreClass(exam.score)">
            <div class="score-value">{{ exam.score }}</div>
            <div class="score-total">/ {{ exam.totalScore }}</div>
          </div>
          <div class="score-text" :class="getScoreClass(exam.score)">
            {{ getScoreText(exam.score) }}
          </div>
        </div>
        
        <div class="stats-section">
          <div class="stat-item">
            <div class="stat-label">答题数</div>
            <div class="stat-value">{{ result.answeredCount }}/{{ result.totalCount }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">正确数</div>
            <div class="stat-value">{{ result.correctCount }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">错误数</div>
            <div class="stat-value">{{ result.wrongCount }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">正确率</div>
            <div class="stat-value">{{ result.correctRate }}%</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">用时</div>
            <div class="stat-value">{{ formatDuration(result.duration) }}</div>
          </div>
        </div>
      </div>
      
      <div class="result-chart">
        <div class="chart-title">得分分布</div>
        <div class="chart-container" ref="scoreChart"></div>
      </div>
      
      <div class="result-analysis">
        <div class="analysis-title">
          <span>答题分析</span>
          <el-switch
            v-model="showWrongOnly"
            active-text="只看错题"
            inactive-text="查看全部"
          ></el-switch>
        </div>
        
        <div v-if="filteredQuestions.length === 0" class="no-questions">
          <el-empty description="没有符合条件的题目"></el-empty>
        </div>
        
        <div v-else class="question-list">
          <div 
            v-for="(question, index) in filteredQuestions" 
            :key="index"
            class="question-item"
            :class="{ 'wrong-answer': !question.isCorrect }"
          >
            <div class="question-header">
              <div class="question-index">第 {{ question.index + 1 }} 题</div>
              <div class="question-type">{{ getQuestionTypeText(question.type) }}</div>
              <div class="question-score">
                <span>得分：</span>
                <span :class="{ 'text-success': question.isCorrect, 'text-danger': !question.isCorrect }">
                  {{ question.score }}
                </span>
                <span> / {{ question.totalScore }}</span>
              </div>
            </div>
            
            <div class="question-content">
              <div class="question-title" v-html="question.content"></div>
              
              <!-- 单选题 -->
              <div v-if="question.type === 'single'" class="question-options">
                <div 
                  v-for="(option, optIndex) in question.options" 
                  :key="optIndex"
                  class="option-item"
                  :class="{
                    'correct-option': option.value === question.correctAnswer,
                    'wrong-option': option.value === question.userAnswer && option.value !== question.correctAnswer
                  }"
                >
                  <span class="option-marker">
                    <i 
                      v-if="option.value === question.correctAnswer" 
                      class="el-icon-check text-success"
                    ></i>
                    <i 
                      v-else-if="option.value === question.userAnswer" 
                      class="el-icon-close text-danger"
                    ></i>
                  </span>
                  <span class="option-text">{{ option.label }}</span>
                </div>
              </div>
              
              <!-- 多选题 -->
              <div v-else-if="question.type === 'multiple'" class="question-options">
                <div 
                  v-for="(option, optIndex) in question.options" 
                  :key="optIndex"
                  class="option-item"
                  :class="{
                    'correct-option': question.correctAnswer.includes(option.value) && question.userAnswer.includes(option.value),
                    'wrong-option': !question.correctAnswer.includes(option.value) && question.userAnswer.includes(option.value),
                    'missed-option': question.correctAnswer.includes(option.value) && !question.userAnswer.includes(option.value)
                  }"
                >
                  <span class="option-marker">
                    <i 
                      v-if="question.correctAnswer.includes(option.value) && question.userAnswer.includes(option.value)" 
                      class="el-icon-check text-success"
                    ></i>
                    <i 
                      v-else-if="!question.correctAnswer.includes(option.value) && question.userAnswer.includes(option.value)" 
                      class="el-icon-close text-danger"
                    ></i>
                    <i 
                      v-else-if="question.correctAnswer.includes(option.value) && !question.userAnswer.includes(option.value)" 
                      class="el-icon-warning text-warning"
                    ></i>
                  </span>
                  <span class="option-text">{{ option.label }}</span>
                </div>
              </div>
              
              <!-- 判断题 -->
              <div v-else-if="question.type === 'boolean'" class="question-options">
                <div 
                  class="option-item"
                  :class="{ 
                    'correct-option': true === question.correctAnswer && true === question.userAnswer,
                    'wrong-option': true === question.userAnswer && true !== question.correctAnswer
                  }"
                >
                  <span class="option-marker">
                    <i 
                      v-if="true === question.correctAnswer && true === question.userAnswer" 
                      class="el-icon-check text-success"
                    ></i>
                    <i 
                      v-else-if="true === question.userAnswer && true !== question.correctAnswer" 
                      class="el-icon-close text-danger"
                    ></i>
                  </span>
                  <span class="option-text">正确</span>
                </div>
                <div 
                  class="option-item"
                  :class="{ 
                    'correct-option': false === question.correctAnswer && false === question.userAnswer,
                    'wrong-option': false === question.userAnswer && false !== question.correctAnswer
                  }"
                >
                  <span class="option-marker">
                    <i 
                      v-if="false === question.correctAnswer && false === question.userAnswer" 
                      class="el-icon-check text-success"
                    ></i>
                    <i 
                      v-else-if="false === question.userAnswer && false !== question.correctAnswer" 
                      class="el-icon-close text-danger"
                    ></i>
                  </span>
                  <span class="option-text">错误</span>
                </div>
              </div>
              
              <!-- 填空题 -->
              <div v-else-if="question.type === 'fill'" class="question-fill">
                <div class="answer-comparison">
                  <div class="user-answer">
                    <div class="answer-label">你的答案：</div>
                    <div class="answer-content" :class="{ 'text-danger': !question.isCorrect }">
                      {{ question.userAnswer || '未作答' }}
                    </div>
                  </div>
                  <div class="correct-answer">
                    <div class="answer-label">正确答案：</div>
                    <div class="answer-content text-success">{{ question.correctAnswer }}</div>
                  </div>
                </div>
              </div>
              
              <!-- 简答题 -->
              <div v-else-if="question.type === 'essay'" class="question-essay">
                <div class="answer-comparison">
                  <div class="user-answer">
                    <div class="answer-label">你的答案：</div>
                    <div class="answer-content">{{ question.userAnswer || '未作答' }}</div>
                  </div>
                  <div class="correct-answer">
                    <div class="answer-label">参考答案：</div>
                    <div class="answer-content">{{ question.correctAnswer }}</div>
                  </div>
                  <div v-if="question.teacherComment" class="teacher-comment">
                    <div class="answer-label">老师评语：</div>
                    <div class="answer-content">{{ question.teacherComment }}</div>
                  </div>
                </div>
              </div>
              
              <div v-if="question.explanation" class="question-explanation">
                <div class="explanation-title">解析：</div>
                <div class="explanation-content" v-html="question.explanation"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([TitleComponent, TooltipComponent, LegendComponent, PieChart, CanvasRenderer])

export default {
  name: 'ExamResult',
  data() {
    return {
      exam: {
        id: '',
        title: '',
        courseName: '',
        type: '',
        startTime: 0,
        endTime: 0,
        score: 0,
        totalScore: 0
      },
      result: {
        answeredCount: 0,
        totalCount: 0,
        correctCount: 0,
        wrongCount: 0,
        correctRate: 0,
        duration: 0
      },
      questions: [],
      showWrongOnly: false,
      scoreChart: null
    }
  },
  computed: {
    filteredQuestions() {
      if (this.showWrongOnly) {
        return this.questions.filter(q => !q.isCorrect)
      }
      return this.questions
    }
  },
  created() {
    this.fetchExamResult()
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  methods: {
    ...mapActions(['getExamResult']),
    async fetchExamResult() {
      try {
        const examId = this.$route.params.id
        
        // 获取考试结果
        const data = await this.getExamResult(examId)
        this.exam = data.exam
        this.result = data.result
        this.questions = data.questions
        
        this.$nextTick(() => {
          this.updateChart()
        })
      } catch (error) {
        console.error('获取考试结果失败', error)
        this.$message.error('获取考试结果失败')
        this.$router.push('/exams')
      }
    },
    getExamTypeText(type) {
      const typeMap = {
        quiz: '随堂测验',
        midterm: '期中考试',
        final: '期末考试'
      }
      return typeMap[type] || '未知类型'
    },
    getQuestionTypeText(type) {
      const typeMap = {
        single: '单选题',
        multiple: '多选题',
        boolean: '判断题',
        fill: '填空题',
        essay: '简答题'
      }
      return typeMap[type] || '未知类型'
    },
    formatDateTime(timestamp) {
      if (!timestamp) return ''
      
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    formatDuration(seconds) {
      if (!seconds) return '0秒'
      
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const remainingSeconds = seconds % 60
      
      let result = ''
      if (hours > 0) {
        result += `${hours}小时`
      }
      if (minutes > 0) {
        result += `${minutes}分钟`
      }
      if (remainingSeconds > 0 || result === '') {
        result += `${remainingSeconds}秒`
      }
      
      return result
    },
    getScoreClass(score) {
      const percentage = (score / this.exam.totalScore) * 100
      if (percentage >= 90) {
        return 'excellent'
      } else if (percentage >= 60) {
        return 'pass'
      } else {
        return 'fail'
      }
    },
    getScoreText(score) {
      const percentage = (score / this.exam.totalScore) * 100
      if (percentage >= 90) {
        return '优秀'
      } else if (percentage >= 80) {
        return '良好'
      } else if (percentage >= 70) {
        return '中等'
      } else if (percentage >= 60) {
        return '及格'
      } else {
        return '不及格'
      }
    },
    initChart() {
      if (!this.$refs.scoreChart) return
      
      this.scoreChart = echarts.init(this.$refs.scoreChart)
      this.updateChart()
      
      window.addEventListener('resize', this.resizeChart)
    },
    updateChart() {
      if (!this.scoreChart) return
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['正确', '错误', '未作答']
        },
        series: [
          {
            name: '答题情况',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { 
                value: this.result.correctCount, 
                name: '正确',
                itemStyle: { color: '#67C23A' }
              },
              { 
                value: this.result.wrongCount, 
                name: '错误',
                itemStyle: { color: '#F56C6C' }
              },
              { 
                value: this.result.totalCount - this.result.answeredCount, 
                name: '未作答',
                itemStyle: { color: '#909399' }
              }
            ]
          }
        ]
      }
      
      this.scoreChart.setOption(option)
    },
    resizeChart() {
      if (this.scoreChart) {
        this.scoreChart.resize()
      }
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart)
    if (this.scoreChart) {
      this.scoreChart.dispose()
      this.scoreChart = null
    }
  }
}
</script>

<style lang="scss" scoped>
.exam-result-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.back-link {
  margin-bottom: 20px;
  
  a {
    color: #606266;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    
    &:hover {
      color: #409EFF;
    }
    
    i {
      margin-right: 5px;
    }
  }
}

.result-card {
  margin-bottom: 30px;
}

.result-header {
  margin-bottom: 30px;
  
  .exam-title {
    font-size: 24px;
    color: #303133;
    margin: 0 0 15px;
  }
  
  .exam-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    color: #606266;
    
    .exam-type {
      background-color: #f0f9eb;
      color: #67c23a;
      padding: 2px 8px;
      border-radius: 3px;
    }
  }
}

.result-summary {
  display: flex;
  margin-bottom: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
  
  .score-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-right: 30px;
    margin-right: 30px;
    border-right: 1px solid #ebeef5;
    
    @media (max-width: 768px) {
      padding-right: 0;
      margin-right: 0;
      border-right: none;
      padding-bottom: 20px;
      margin-bottom: 20px;
      border-bottom: 1px solid #ebeef5;
    }
    
    .score-circle {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-bottom: 15px;
      
      &.excellent {
        background-color: #f0f9eb;
        color: #67c23a;
      }
      
      &.pass {
        background-color: #ecf5ff;
        color: #409EFF;
      }
      
      &.fail {
        background-color: #fef0f0;
        color: #f56c6c;
      }
      
      .score-value {
        font-size: 36px;
        font-weight: bold;
      }
      
      .score-total {
        font-size: 16px;
      }
    }
    
    .score-text {
      font-size: 18px;
      font-weight: bold;
      
      &.excellent {
        color: #67c23a;
      }
      
      &.pass {
        color: #409EFF;
      }
      
      &.fail {
        color: #f56c6c;
      }
    }
  }
  
  .stats-section {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 20px;
    
    .stat-item {
      text-align: center;
      
      .stat-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 5px;
      }
      
      .stat-value {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
}

.result-chart {
  margin-bottom: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
  
  .chart-title {
    font-size: 18px;
    color: #303133;
    margin-bottom: 20px;
    font-weight: bold;
  }
  
  .chart-container {
    height: 300px;
  }
}

.result-analysis {
  .analysis-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    font-size: 18px;
    color: #303133;
    font-weight: bold;
  }
  
  .no-questions {
    padding: 30px 0;
  }
  
  .question-list {
    .question-item {
      margin-bottom: 30px;
      padding-bottom: 30px;
      border-bottom: 1px solid #ebeef5;
      
      &:last-child {
        margin-bottom: 0;
        padding-bottom: 0;
        border-bottom: none;
      }
      
      &.wrong-answer {
        background-color: #fff9f9;
        padding: 15px;
        border-radius: 4px;
        border-left: 4px solid #f56c6c;
      }
      
      .question-header {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        
        .question-index {
          font-weight: bold;
          margin-right: 15px;
        }
        
        .question-type {
          background-color: #ecf5ff;
          color: #409EFF;
          padding: 2px 8px;
          border-radius: 3px;
          margin-right: 15px;
        }
        
        .question-score {
          margin-left: auto;
        }
      }
      
      .question-content {
        .question-title {
          font-size: 16px;
          color: #303133;
          margin-bottom: 15px;
          line-height: 1.6;
        }
        
        .question-options {
          margin-bottom: 15px;
          
          .option-item {
            display: flex;
            align-items: flex-start;
            margin-bottom: 10px;
            padding: 8px 12px;
            border-radius: 4px;
            
            &.correct-option {
              background-color: #f0f9eb;
            }
            
            &.wrong-option {
              background-color: #fef0f0;
            }
            
            &.missed-option {
              background-color: #fdf6ec;
            }
            
            .option-marker {
              margin-right: 10px;
              width: 20px;
              text-align: center;
            }
            
            .option-text {
              flex: 1;
            }
          }
        }
        
        .question-fill, .question-essay {
          margin-bottom: 15px;
          
          .answer-comparison {
            .user-answer, .correct-answer, .teacher-comment {
              margin-bottom: 10px;
              
              .answer-label {
                font-weight: bold;
                margin-bottom: 5px;
              }
              
              .answer-content {
                padding: 10px;
                background-color: #f5f7fa;
                border-radius: 4px;
                white-space: pre-wrap;
              }
            }
          }
        }
        
        .question-explanation {
          margin-top: 15px;
          padding: 15px;
          background-color: #f5f7fa;
          border-radius: 4px;
          
          .explanation-title {
            font-weight: bold;
            margin-bottom: 10px;
          }
          
          .explanation-content {
            color: #606266;
            line-height: 1.6;
          }
        }
      }
    }
  }
}

.text-success {
  color: #67c23a;
}

.text-danger {
  color: #f56c6c;
}

.text-warning {
  color: #e6a23c;
}
</style> 